package com.zhao.controller;

import com.zhao.bean.R;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
public class CommonUploadController {

    @Value("${reggie.file-path}")
    private String uploadPath;

    //文件下载
    @GetMapping("/common/download/{fileName}")
    public R<String> download(@PathVariable String fileName, HttpServletResponse response){
        System.out.println(":::::::::::::"+fileName);
       //创建File对象
        try {
            File file = new File(uploadPath,fileName);
            //调用输出流读取文件到缓冲区
            FileInputStream stream = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len=0;
            ServletOutputStream outputStream = response.getOutputStream();
            while ((len=stream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }
            //关闭
            stream.close();
            outputStream.close();
            return R.success("下载成功");
        } catch (IOException e) {
            e.printStackTrace();
            return R.success("下载失败");
        }
    }

    //文件上传
    @PostMapping("/common/upload")
    public R upload(MultipartFile file) throws IOException {
        //获取新的文件名
        String replace = UUID.randomUUID().toString().replace("-", "");

        String filename = file.getOriginalFilename();
        String substring = filename.substring(filename.lastIndexOf("."));
        //文件名和后缀名进行拼接成一个完整的新的文件名
        replace+=substring;
        //进行判断文件夹是否为空，如果为空，就新建一个文件夹
        File file1 = new File(uploadPath);
        if (!file1.exists()){
            file1.mkdirs();
        }
        //把接收到文件给保存起来
        File file2 = new File(uploadPath + replace);
        //将文件保存
        file.transferTo(file2);

        return R.success(replace);
    }
}
